<template>
    <view class="performance">
        <uni-nav-bar fixed left-icon="left" title="目标业绩" @clickLeft="backHandle" @clickRight="openHandle" class="unibarS">
            <block slot="right">
                <svg-icon svgPath="/static/svg/icon-shaixuan.svg" color="#0C1019" size="18px" />
			</block>
        </uni-nav-bar>

        <!-- 数据统计 柱状图 -->
        <view style="background-color: rgba(255, 255, 255, 1);">
            <view class="title">数据统计</view>
            <l-echart ref="chartColumnar"></l-echart>
        </view>
        <!-- 金额汇总 -->
        <view class="money-summary">
            <view>
                <view class="label">目标金额</view>
                <view class="num">￥{{ yearTotal.annualTarget }}</view>
            </view>
            <view>
                <view class="label">成交金额</view>
                <view class="num">￥{{ yearTotal.totalAmount }}</view>
            </view>
            <view>
                <view class="label">完成率</view>
                <view class="num">{{ yearTotal.conversionRate }}%</view>
            </view>
        </view>
        <!-- 表格 -->
         <view>
            <uni-table ref="table" emptyText="暂无更多数据">
                <uni-tr>
                    <uni-th width="80" align="center">时间</uni-th>
                    <uni-th width="100" align="center">目标金额</uni-th>
                    <uni-th width="100" align="center">成交金额</uni-th>
                    <uni-th width="100" align="center">成交订单</uni-th>
                    <uni-th width="100" align="center">完成率</uni-th>
                    <uni-th width="100" align="center">平均客单价</uni-th>
                </uni-tr>
                <uni-tr v-for="(item, index) in tableData" :key="index">
                    <uni-td align="center">{{ item.time }}</uni-td>
                    <uni-td align="center">{{ item.annualTarget }}</uni-td>
                    <uni-td align="center">{{ item.totalAmount }}</uni-td>
                    <uni-td align="center">{{ item.totalCount }}</uni-td>
                    <uni-td align="center">{{ item.conversionRate }}</uni-td>
                    <uni-td align="center">{{ item.average }}</uni-td>
                </uni-tr>
            </uni-table>
         </view>
         <uni-popup style="width: 100%;" ref="popup" type="right" @maskClick="maskClick" border-radius="10px 10px 0 0">
            <view class="drawer-box">
                <view class="drawer-content">
                    <u--form labelPosition="top" ref="uForm" labelWidth="100">
                        <u-form-item label="类型" border
                            ref="item1">
                            <view class="drawer-classify">
                                <view v-for="(item, index) in bs_performance_targettype" :key="index" @click="changeTime(item.dictValue)" :class="{ active: statisticsQuery.targetType == item.dictValue }">{{ item.dictLabel }}</view>
                            </view>
                        </u-form-item>
                        <u-form-item class="search-item-box" label="时间" border ref="item1">
                            <view style="width: 100%;">
                                <picker mode="date" fields="year" :value="selectedYear" @change="bindDateChange">
                                    <view v-if="statisticsQuery.financialYear" style="width: 100%;">{{ statisticsQuery.financialYear }}年</view>
                                    <view v-else>请选择年份</view>
                                </picker>
                            </view>
                            <u-icon slot="right" name="clock"></u-icon>
                        </u-form-item>
                        <u-form-item class="search-item-box" label="部门" border ref="item1" @click="bindDpet">
                            <view style="width: 100%;">
                                <view v-if="statisticsQuery.department" style="width: 100%;">{{ statisticsQuery.departmentName }}年</view>
                                <view v-else>请选择部门</view>
                            </view>
                            <u-icon slot="right" name="arrow-right"></u-icon>
                        </u-form-item>
                        <u-form-item label="人员" border ref="item1">
                            <view class="flex-sub">
                                <view class="flex-sub-item" v-for="item in statisticsQuery.createBy" :key="item.userId">
                                    <u-avatar
                                        :src="item.avatar" class="avatar" :size="30">
                                    </u-avatar>
                                    <view class="name">{{ item.userName }}</view>
                                </view>
                            </view>
                            <u-icon  @click="selectHandle()" slot="right" name="plus-circle-fill" size="30"></u-icon>
                        </u-form-item>
                    </u--form>
                </view>
                <view class="drawer-footer">
                    <view class="drawer-footer-res" @click="reset">重置</view>
                    <view class="drawer-footer-sub" @click="submit">确定</view>
                </view>
            </view>
		</uni-popup>
        <!-- 选择跟进日期 -->
		<uni-calendar ref="calendar" class="uni-calendar--hook" :range="true" :clear-date="true" :date="infoCalendar.date"
		:insert="infoCalendar.insert" @confirm="confirmCalendar" @close="closeCalendar" />
    </view>
</template>

<script>
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
import { calculateDateRange } from '@/common/utils'
export default {
    data() {
        return {
            loading: false,
            queryData: {
                performanceType: 2,
                targetType: 1,
                createBy: [],
                financialYear: null,
                department: null,
                departmentName: null
            },
            tableData: [],
            // 柱状图数据
            // 每月目标
            annualTargetData: [],
            // 每月金额
            totalAmountData: [],

            yearTotal: {},

            statisticsQuery: {
				targetType: 1,
                createBy: [],
                financialYear: null,
                department: null,
                departmentName: null
			},
            infoCalendar: {
                insert: false,
                selected: []
            },
            selectedYear: new Date().getFullYear(), // 初始化为当前年份
            bs_performance_targettype: []
        }
    },
    created() {

        this.bs_performance_targettype = JSON.parse(uni.getStorageSync('bs_performance_targettype'))
        this.queryData.targetType = this.bs_performance_targettype[0].dictValue
        this.statisticsQuery.targetType = this.bs_performance_targettype[0].dictValue

        const currentYear = new Date().getFullYear();
        this.queryData.financialYear = currentYear

        this.getTotalMoney()
        this.getPersonage()
        setTimeout(() => {
            // 柱状图
            this.initChartColumnar()
        }, 500)
    },
    methods: {
        getTotalMoney() {
            let obj = JSON.parse(JSON.stringify(this.queryData))
            obj['ids'] = this.queryData.createBy.map(item => item.userId)
            delete obj.createBy
            this.$http.get('/app/statistics/performance/yearList', obj).then(res => {
                if (res.code == 200) {
                    this.yearTotal = res.data
                }
            })
        },
        getPersonage() {
            let obj = JSON.parse(JSON.stringify(this.queryData))
            obj['ids'] = this.queryData.createBy.map(item => item.userId)
            delete obj.createBy
            this.$http.get('/app/statistics/performance/monthList', obj).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data
                    this.annualTargetData = res.data.map(item => {
                        return item.annualTarget
                    })
                    this.totalAmountData = res.data.map(item => {
                        return item.totalAmount
                    })
                }
            })
        },
        initChartColumnar() {
            this.$refs.chartColumnar.init(echarts, chart => {
                const option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    // legend: {
                    //     show: false,
                    //     data: ['每月目标', '每月金额']
                    // },
                    grid: {
                        top: 'top',
                        left: '16',
                        right: '16',
                        bottom: '16',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value',
                        boundaryGap: [0, 0.01],
                    },
                    yAxis: {
                        type: 'category',
                        // data: ['巴西', '印尼', '美国', '印度', '中国', '世界人口(万)']
                        data: ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06', '2024-07', '2024-08', '2024-09', '2024-10', '2024-11', '2024-12']
                    },
                    series: [{
                            name: '每月目标',
                            type: 'bar',
                            data: this.annualTargetData
                        },
                        {
                            name: '每月金额',
                            type: 'bar',
                            data: this.totalAmountData
                        }
                    ]
                }
                chart.setOption(option);

            });
        },
        backHandle() {
            uni.navigateBack()
        },
        openHandle() {
            console.log('open');
            Object.keys(this.queryData).forEach(key => {
				if (this.statisticsQuery.hasOwnProperty(key)) {
					this.statisticsQuery[key] = this.queryData[key];
				}
			});
            this.$refs.popup.open()
        },
               // 打开日历
		openCalendar(type) {
			this.$refs.calendar.open()
        },
        // 确定日期
        confirmCalendar(e) {
			if(e.range.before && e.range.after) {
				let arr = []
				arr[0] = e.range.before? e.range.before : null
				arr[1] = e.range.after? e.range.after : null
				this.tempSearchObj.startTime = arr[0]
				this.tempSearchObj.endTime = arr[1]
			} else {
				this.tempSearchObj.startTime = null
				this.tempSearchObj.endTime = null
				return
			}
			this.tempSearchObj.type = null
        },
        // 关闭日历
        closeCalendar() { },
        changeTime(type) {
			this.statisticsQuery.targetType = type
		},
        bindDateChange(e) {
            console.log(e)
            const selectedYearValue = new Date(e.detail.value).getFullYear();
            this.statisticsQuery.financialYear = e.detail.value;
            console.log(this.statisticsQuery.financialYear);
        },
        reset() {
            this.statisticsQuery = {
				targetType: this.bs_performance_targettype[0].dictValue,
                createBy: [],
                financialYear: new Date().getFullYear(),
                department: null,
                departmentName: null
			}
        },
        submit() {
            Object.keys(this.statisticsQuery).forEach(key => {
				if (this.queryData.hasOwnProperty(key)) {
					this.queryData[key] = this.statisticsQuery[key];
				}
			});
            console.log(this.queryData)
            this.getTotalMoney()
            this.getPersonage()
            this.$refs.popup.close()
        },
        // 选择业务员
        selectHandle(type) {
            let that = this
            uni.navigateTo({
                url: '/pages/crm/customer/selectSalesmanMultiple',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
						console.log(data)
                        that.statisticsQuery.createBy = data.data
                    },
                },
                success: function (res) {
					let list = JSON.parse(JSON.stringify(that.statisticsQuery.createBy))
                    res.eventChannel.emit('emitDataHandle', { data: list, type: true })
                }
            });
        },
        bindDpet() {
            let that = this
            uni.navigateTo({
                url: '/pages/crm/customer/selectDpet',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        that.statisticsQuery.department = data.data.deptId
                        that.statisticsQuery.departmentName = data.data.deptName
                    },
                },
                success: function (res) {
                    // console.log('success:' + JSON.stringify(res))
                    let obj = {
                        deptId: that.statisticsQuery.department,
                        deptName: that.statisticsQuery.departmentName,
                    }
                    res.eventChannel.emit('emitDataHandle', { data: obj })
                }
            });
        },
        maskClick() {
            
        }
    }
}
</script>

<style lang="scss" scoped>
    .title {
        padding: 16px;
        font-size: 32rpx;
        font-weight: 500;
        color: rgba(12, 16, 25, 1);
    }
    .money-summary {
        display: flex;
        justify-content: space-around;
        background: rgba(255, 255, 255, 1);
        margin: 32rpx 0;
        padding: 32rpx 0;
        > view {
            text-align: center;
            .label {
                font-size: 24rpx;
                font-weight: 400;
                color: rgba(103, 117, 133, 1);
                margin-bottom: 14rpx;
            }
            .num {
                font-size: 28rpx;
                font-weight: 500;
                color: rgba(12, 16, 25, 1);
            }
        }
    }
    .drawer-box {
        width: 622rpx;
        height: 100vh;
        display: flex;
        flex-direction: column;
        background-color: white;

        .drawer-content {
            flex: 1;
            overflow-y: auto;
            padding: 0 24rpx;

            .drawer-classify {
                display: flex;
                flex-wrap: wrap;

                >view {
                    font-size: 28rpx;
                    font-weight: 400;
                    color: rgba(103, 117, 133, 1);
                    border-radius: 16rpx;
                    background: #FFFFFFFF;
                    border: 2rpx solid #67758566;
                    padding: 16rpx 0;
                    width: 174rpx;
                    margin-right: 20rpx;
                    margin-bottom: 20rpx;
                    text-align: center;
                }

                :nth-child(3n) {
                    margin-right: 0;
                }

                .active {
                    border: none;
                    background: #4DACB1FF;
                    color: rgba(255, 255, 255, 1);
                }
            }
            .search-item-box {
                /deep/.u-form-item__body__right {
                    border: 2rpx solid rgba(103, 117, 133, 0.4);
                    padding: 16rpx 16rpx;
                    border-radius: 8rpx;
                }
            }
        }

        .drawer-footer {
            padding: 24rpx;
            display: flex;

            >view {
                border-radius: 8rpx;
                text-align: center;
                height: 44px;
                line-height: 44px;
                font-size: 32rpx;
                font-weight: 500;
            }

            .drawer-footer-res {
                height: 42px;
                width: 154rpx;
                background: #FFFFFFFF;
                border: 3rpx solid #4DACB1FF;
                color: rgba(77, 172, 177, 1);
                margin-right: 20rpx;
            }

            .drawer-footer-sub {
                flex: 1;
                background: #4DACB1FF;
                color: #FFFFFFFF;
            }
        }
    }

.flex-sub {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    .flex-sub-item {
        margin-right: 10rpx;
        margin-bottom: 10rpx;
        width: 100rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        .name {
            // 超出显示省略号
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            width: 100%;
            font-size: 28rpx;

        }
    }
}
</style>